﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PragmaTouchUtils;
using System.Data.SqlClient;

namespace eBook.WinApp
{
  public partial class ucDatabaseOptions : ucOptionEditorBase, IConfigContentEditor
  {
    private DatabaseOptions _options;
    public ucDatabaseOptions()
    {
      InitializeComponent();
    
      this.ItemClassName = "DatabaseOptions"; 
      this.Caption = "Database"; 
    }

    protected override void LoadInitial()
    { 
      _options = _currentConfig.GetConfigContentItem(this.ItemClassName) as DatabaseOptions;
      if ( _options == null )
        throw new Exception(string.Format("Configuration content does not contain {0} item!", this.ItemClassName));

      txtServer.DataBindTo(_options, "Server", this.ControlValueChanged);
      txtDatabase.DataBindTo(_options, "Database", this.ControlValueChanged);
      chkIntegratedSecurity.DataBindTo(_options, "IntegratedSecurity", this.ControlValueChanged);
      txtUsername.DataBindTo(_options, "Username", this.ControlValueChanged);
      txtPassword.DataBindTo(_options, "Password", this.ControlValueChanged);

      this.RequireAuthentication(!chkIntegratedSecurity.Checked);
    }

    private void ControlValueChanged(object sender, EventArgs e)
    {
      this.Modified = true;
      if ( sender == chkIntegratedSecurity)
        this.RequireAuthentication(!chkIntegratedSecurity.Checked);
    }

    private void RequireAuthentication(bool enabled)
    {
      txtUsername.Enabled = enabled;
      txtPassword.Enabled = enabled;
    }

    private void btnTest_Click(object sender, EventArgs e)
    {
      try
      {
        string connectionString = _options.BuildConnectionString();
        using ( SqlConnection connection = new SqlConnection(connectionString) )
        {
          connection.Open();
          PragmaTouchUtils.MessageBoxHelper.ShowInfo("Test connection successfull");
        }
      }
      catch ( Exception ex)
      {
        PragmaTouchUtils.MessageBoxHelper.ShowError(ex);
        
      }
    }

  }


}
